package com.ipc.app.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ipc.app.biz.UserBiz;
import com.ipc.app.model.User;
import com.ipc.app.web.form.UserRegistrationForm;

/**
 * @author haijie.zhang
 * 
 */
@Controller
@RequestMapping(value = "/jsp/userRegistration.do")
public class UserRegistrationAction {

	@Autowired
	private Validator validator;

	@Autowired
	private UserBiz userBiz;

	@RequestMapping(method = RequestMethod.GET)
	public String userRegistrationView(ModelMap model) {
		model.addAttribute("userRegistrationForm", new UserRegistrationForm());
		return "registration";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String userRegistration(@ModelAttribute("userRegistrationForm")
	UserRegistrationForm userRegistrationForm, BindingResult result) {

		// TODO:密码校验
		validator.validate(userRegistrationForm, result);
		if (result.hasErrors()) {
			return "registration";
		}
		User user = assembleUser(userRegistrationForm);
		userBiz.createUser(user);

		return "registrationSuccess";
	}

	private User assembleUser(UserRegistrationForm userRegistrationForm) {
		User user = new User();
		user.setUserName(userRegistrationForm.getUsername());
		user.setMobile(userRegistrationForm.getMobile());
		user.setPassword(userRegistrationForm.getPassword());
		user.setUserType(userRegistrationForm.getUserType());

		return user;
	}
}
